package com.iplant.basic.serviceImpl.dao.fmc;

import com.iplant.base.po.enums.DBSchemas;
import com.iplant.basic.service.po.fmc.FMCStationFixtures;
import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.enums.ExceptionTypes;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.BaseDAO;
import com.iplant.basic.service.po.bms.BMSEmployee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class FMCStationFixturesDAO extends BaseDAO {

    private static FMCStationFixturesDAO Instance = null;
    private static Logger logger = LoggerFactory.getLogger(FMCStationFixturesDAO.class);

    private FMCStationFixturesDAO() {
        super();
        setTableName("fmc_stationfixtrues");
    }

    public static FMCStationFixturesDAO getInstance() {
        if (Instance == null)
            Instance = new FMCStationFixturesDAO();
        return Instance;
    }

    public void FMC_UpdateStationFixtures(BMSEmployee wLoginUser, FMCStationFixtures wStationFixtures,
                                          OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);

        try {
            if (wStationFixtures == null || StringUtils.isEmpty(wStationFixtures.Name)) {
                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
            }
            FMCStationFixtures wStationFixturesO = this.FMC_CheckStationFixtures(wLoginUser, wStationFixtures,
                    wErrorCode);
            if (wStationFixturesO.ID > 0) {
                wErrorCode.set(ExceptionTypes.Duplication.getValue());
            }
            if (wErrorCode.Result != 0)
                return;

            Map<String, Object> wParams = new HashMap<String, Object>();

            wParams.put("StationID", wStationFixtures.StationID);

            wParams.put("DeviceID", StringUtils.Join(",", wStationFixtures.DeviceID));

            wParams.put("Name", wStationFixtures.Name);
            wParams.put("Code", wStationFixtures.Code);
            wParams.put("Description", wStationFixtures.Description);

            wParams.put("EditorID", wLoginUser.getID());
            wParams.put("EditTime", Calendar.getInstance());
            wParams.put("Active", wStationFixtures.Active);

            if (wStationFixtures.ID > 0) {
                wParams.put("ID", wStationFixtures.ID);
                super.Update(super.getTableName("fmc_stationfixtrues"), "ID", wParams);
            } else {
                wParams.put("CreatorID", wLoginUser.getID());
                wParams.put("CreateTime", Calendar.getInstance());
                wStationFixtures.ID = super.Insert(super.getTableName("fmc_stationfixtrues"), wParams);
            }

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("FMC_UpdateStationFixtures", ex);
        }
    }

    public void FMC_ActiveStationFixtures(BMSEmployee wLoginUser, FMCStationFixtures wStationFixtures, int wActive,
                                          OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        // 判断客户信息是否存在(中国：统一社会信用代码，国外:提醒是否有重复）

        try {
            if (wStationFixtures == null || wStationFixtures.ID <= 0) {
                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
            }

            Map<String, Object> wParams = new HashMap<String, Object>();

            wParams.put("ID", wStationFixtures.ID);
            wParams.put("EditorID", wLoginUser.getID());
            wParams.put("EditTime", Calendar.getInstance());
            wParams.put("Active", wActive);
            super.Update(super.getTableName("fmc_stationfixtrues"), "ID", wParams);

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());

            logger.error("FMC_ActiveStationFixtures", ex);
        }
    }

    public List<FMCStationFixtures> FMC_QueryStationFixturesList(BMSEmployee wLoginUser, int wFactoryID,
                                                                 int wWorkshopID, int wLineID, int wWorkAreaID,
                                                                 List<Integer> wStationID, int wDeviceID, String wName,
                                                                 int wActive, Pagination wPagination,
                                                                 OutResult<Integer> wErrorCode) {
        return this.FMC_QueryStationFixturesList(wLoginUser, -1, "", wFactoryID, wWorkshopID, wLineID, wWorkAreaID,
                wStationID, wDeviceID, wName, wActive, wPagination, wErrorCode);
    }

    private List<FMCStationFixtures> FMC_QueryStationFixturesList(BMSEmployee wLoginUser, int wID, String wCode,
                                                                  int wFactoryID, int wWorkshopID, int wLineID,
                                                                  int wWorkAreaID, List<Integer> wStationID,
                                                                  int wDeviceID,
                                                                  String wName, int wActive, Pagination wPagination,
                                                                  OutResult<Integer> wErrorCode) {
        List<FMCStationFixtures> wFMCStationFixturesList = new ArrayList<FMCStationFixtures>();
        wErrorCode.set(0);

        try {
            if (wStationID == null)
                wStationID = new ArrayList<Integer>();

            wStationID.removeIf(p -> p <= 0);

            // Step02:查询
            Map<String, Object> wParams = new HashMap<String, Object>();
            String wSQLText = "";
            wSQLText = StringUtils.Format("Select t.*,t9.WorkAreaID,t1.WorkshopID,t5.FactoryID,"
                            + " t9.Name as StationName,t9.Code as  StationCode,"
                            + " t1.Name as WorkAreaName t1.Code as WorkAreaCode,t2.Name as FactoryName,t2.Code as " +
                            "FactoryCode,"
                            + " t5.Name as WorkshopName,t5.Code as WorkshopCode,group_concat(distinct t7.Name) as " +
                            "DeviceName,"
                            + " group_concat(distinct t7.Code) as DeviceCode,t3.Name as CreatorName ,t4.Name as " +
                            "EditorName "
                            + " from {0}.fmc_stationfixtrues t  "
                            + " left join {0}.fmc_station t9 on t.StationID=t9.ID "
                            + " left join {0}.fmc_workarea t1 on t9.WorkAreaID=t1.ID "
                            + " left join {0}.mbs_user t3 on t.CreatorID=t3.ID "
                            + " left join {0}.mbs_user t4 on t.EditorID=t4.ID "
                            + " left join {0}.fmc_workshop t5 on t1.WorkshopID=t5.ID "
                            + " left join {0}.fmc_factory t2 on t5.FactoryID=t2.ID "
                            + " left join {2}.dms_device_ledger t7 on find_in_set(t7.ID,t.DeviceID) and t7.Active=1 "
                            + " where (:ID<=0 or  t.ID=:ID) and (:Code =''''  or  t.Code=:Code)"
                            + " AND (:FactoryID<=0 or  t5.FactoryID=:FactoryID) "
                            + " AND (:WorkshopID<=0 or  t1.WorkshopID=:WorkshopID)  "
                            + " AND (:WorkAreaID<=0 or  t9.WorkAreaID=:WorkAreaID)  "
                            + " AND (:Active<0 or  t.Active=:Active) AND (:Name = '''' or  t.Name like :Name)"
                            + " AND (:DeviceID<=0 or find_in_set(:DeviceID,t.DeviceID) )"
                            + " AND (:StationID = '''' or  t.StationID IN ({1}) ) group by t.ID ", super.getDBName(),
                    wStationID.size() > 0 ? StringUtils.Join(",", wStationID) : "0", DBSchemas.AMS.getDBName());

            wSQLText = this.DMLChange(wSQLText);

            wParams.put("ID", wID);
            wParams.put("FactoryID", wFactoryID);
            wParams.put("WorkshopID", wWorkshopID);
            wParams.put("WorkAreaID", wWorkAreaID);
            wParams.put("LineID", wLineID);
            wParams.put("DeviceID", wDeviceID);
            wParams.put("StationID", StringUtils.Join(",", wStationID));
            wParams.put("Code", wCode);
            wParams.put("Active", wActive);
            wParams.put("Name", StringUtils.isEmpty(wName) ? "" : ("%" + wName + "%"));

            List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParams, wPagination);
            FMCStationFixtures wFMCStationFixtures = null;
            for (Map<String, Object> wSqlDataReader : wQueryResultList) {
                wFMCStationFixtures = new FMCStationFixtures();
                wFMCStationFixtures.ID = StringUtils.parseInt(wSqlDataReader.get("ID"));
                wFMCStationFixtures.Code = StringUtils.parseString(wSqlDataReader.get("Code"));
                wFMCStationFixtures.Name = StringUtils.parseString(wSqlDataReader.get("Name"));
                wFMCStationFixtures.StationID = StringUtils.parseInt(wSqlDataReader.get("StationID"));
                wFMCStationFixtures.StationCode = StringUtils.parseString(wSqlDataReader.get("StationCode"));
                wFMCStationFixtures.StationName = StringUtils.parseString(wSqlDataReader.get("StationName"));
                wFMCStationFixtures.WorkAreaID = StringUtils.parseInt(wSqlDataReader.get("WorkAreaID"));
                wFMCStationFixtures.WorkAreaCode = StringUtils.parseString(wSqlDataReader.get("WorkAreaCode"));
                wFMCStationFixtures.WorkAreaName = StringUtils.parseString(wSqlDataReader.get("WorkAreaName"));
                wFMCStationFixtures.FactoryID = StringUtils.parseInt(wSqlDataReader.get("FactoryID"));
                wFMCStationFixtures.FactoryCode = StringUtils.parseString(wSqlDataReader.get("FactoryCode"));
                wFMCStationFixtures.FactoryName = StringUtils.parseString(wSqlDataReader.get("FactoryName"));
                wFMCStationFixtures.WorkshopID = StringUtils.parseInt(wSqlDataReader.get("WorkshopID"));
                wFMCStationFixtures.WorkshopCode = StringUtils.parseString(wSqlDataReader.get("WorkshopCode"));
                wFMCStationFixtures.WorkshopName = StringUtils.parseString(wSqlDataReader.get("WorkshopName"));

                wFMCStationFixtures.DeviceID = StringUtils.parseIntList(wSqlDataReader.get("DeviceID"), ",");
                wFMCStationFixtures.DeviceName = StringUtils.parseString(wSqlDataReader.get("DeviceName"));
                wFMCStationFixtures.DeviceCode = StringUtils.parseString(wSqlDataReader.get("DeviceCode"));
                wFMCStationFixtures.Active = StringUtils.parseInt(wSqlDataReader.get("Active"));
                wFMCStationFixtures.CreatorID = StringUtils.parseInt(wSqlDataReader.get("CreatorID"));
                wFMCStationFixtures.EditorID = StringUtils.parseInt(wSqlDataReader.get("EditorID"));
                wFMCStationFixtures.CreatorName = StringUtils.parseString(wSqlDataReader.get("CreatorName"));
                wFMCStationFixtures.EditorName = StringUtils.parseString(wSqlDataReader.get("EditorName"));
                wFMCStationFixtures.CreateTime = StringUtils.parseCalendar(wSqlDataReader.get("CreateTime"));
                wFMCStationFixtures.EditTime = StringUtils.parseCalendar(wSqlDataReader.get("EditTime"));
                wFMCStationFixtures.Description = StringUtils.parseString(wSqlDataReader.get("Description"));

                wFMCStationFixturesList.add(wFMCStationFixtures);
            }

            // Step03:配置系统
        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("FMC_QueryStationFixturesList", ex);
        }
        return wFMCStationFixturesList;
    }

    public FMCStationFixtures FMC_QueryStationFixtures(BMSEmployee wLoginUser, int wID, String wCode,
                                                       OutResult<Integer> wErrorCode) {
        FMCStationFixtures wResult = new FMCStationFixtures();
        wErrorCode.set(0);

        try {
            List<FMCStationFixtures> wList = null;
            if (wID > 0) {
                wList = this.FMC_QueryStationFixturesList(wLoginUser, wID, "", -1, -1, -1, -1, null, -1, "", -1,
                        Pagination.getDefault(), wErrorCode);

            } else if (StringUtils.isNotEmpty(wCode)) {
                wList = this.FMC_QueryStationFixturesList(wLoginUser, -1, wCode, -1, -1, -1, -1, null, -1, "", -1,
                        Pagination.getDefault(), wErrorCode);
            }
            if (wList != null && wList.size() > 0) {
                wResult = wList.get(0);
            }
        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("FMC_QueryStationFixturesByID", ex);
        }
        return wResult;
    }

    public FMCStationFixtures FMC_CheckStationFixtures(BMSEmployee wLoginUser, FMCStationFixtures wFMCStationFixtures,
                                                       OutResult<Integer> wErrorCode) {
        FMCStationFixtures wStationFixtures = new FMCStationFixtures();
        wErrorCode.set(0);

        try {

            // Step0:查询
            Map<String, Object> wParams = new HashMap<String, Object>();
            String wSQLText = StringUtils.Format("Select * from {0}.fmc_stationfixtrues "
                            + " where ID!=:ID and ((FactoryID=:FactoryID AND  Name =:Name) or (:Code != '''' and Code=:Code)) ",
                    super.getDBName());
            wParams.put("ID", wFMCStationFixtures.ID);
            wParams.put("FactoryID", wFMCStationFixtures.FactoryID);
            wParams.put("Name", wFMCStationFixtures.Name);
            wParams.put("Code", wFMCStationFixtures.Code);

            wSQLText = this.DMLChange(wSQLText);
            List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParams);
            for (Map<String, Object> wSqlDataReader : wQueryResultList) {
                wStationFixtures.ID = StringUtils.parseInt(wSqlDataReader.get("ID"));
                wStationFixtures.FactoryID = StringUtils.parseInt(wSqlDataReader.get("FactoryID"));
                wStationFixtures.Name = StringUtils.parseString(wSqlDataReader.get("Name"));
                wStationFixtures.Code = StringUtils.parseString(wSqlDataReader.get("Code"));

                wStationFixtures.CreatorID = StringUtils.parseInt(wSqlDataReader.get("CreatorID"));
                wStationFixtures.CreateTime = StringUtils.parseCalendar(wSqlDataReader.get("CreateTime"));
                wStationFixtures.EditorID = StringUtils.parseInt(wSqlDataReader.get("EditorID"));
                wStationFixtures.EditTime = StringUtils.parseCalendar(wSqlDataReader.get("EditTime"));
                wStationFixtures.Active = StringUtils.parseInt(wSqlDataReader.get("Active"));

            }

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("FMC_CheckStationFixtures", ex);
        }
        return wStationFixtures;
    }

}
